package com.srwl.mytx.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.TaskAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Task;
import com.srwl.mytx.service.TaskService;
import com.srwl.mytx.widget.NodataFooter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 悬赏主题任务领取记录
 */
public class TaskReceivedRecordFragment extends Fragment {
    private static final String TAG = "TaskReceived";
    private Boolean hasNextPage;

    public static TaskReceivedRecordFragment newInstance(String topicId) {
        TaskReceivedRecordFragment taskReceivedRecordFragment = new TaskReceivedRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString("topicId", topicId);
        taskReceivedRecordFragment.setArguments(bundle);
        return taskReceivedRecordFragment;
    }

    private int page = 1;
    private MaterialSmoothRefreshLayout refreshLayout;
    private RecyclerView rv_task;
    private ProgressBar progressBar;
    private TaskAdapter taskAdapter;
    private List<Task> taskList = new ArrayList<>();
    private String topicId;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.task_received_record_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            topicId = arguments.getString("topicId");
        }
        refreshLayout = getView().findViewById(R.id.refresh_layout);
        rv_task = getView().findViewById(R.id.rv_task);
        progressBar = getView().findViewById(R.id.progress_bar);
        taskAdapter = new TaskAdapter(getActivity(), taskList);
        rv_task.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_task.setAdapter(taskAdapter);
        loadData(true, false);
        initRefreshLayout();
    }

    private void initRefreshLayout() {
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;
                loadData(false, true);
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }

    private void loadData(boolean isFirst, boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(topicId)) {
            Log.e(TAG, "loadData: 主题ID 为空，，");
            return;
        }
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }
        Map<String, Object> body = new HashMap<>();
        int SIZE = 20;
        body.put("size", SIZE);
        body.put("page", page);
        body.put("topicId", topicId);
        RetrofitManager.getInstance().createRequest(TaskService.class)
                .getTasksByTopicId(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (page == 1) {
                                taskAdapter.showErrorView();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (page == 1) {
                                taskAdapter.showErrorView();
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 获取清单数据完成");
                        JSONObject pageInfo = (JSONObject) result.getData();
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 2000);
                        }
                        List<Task> statements = pageInfo.getJSONArray("list").toJavaList(Task.class);
                        if (isRefresh) {
                            taskList.clear();
                        }
                        if (statements.size() > 0) {
                            taskList.addAll(statements);
                            taskAdapter.showNormalView();
                            page++;
                        } else {
                            taskAdapter.showNoDataView();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            taskAdapter.showErrorView();
                        }
                        t.printStackTrace();
                    }
                });
    }


}
